<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="学生姓名" prop="studentName">
            <el-input v-model="queryParams.studentName" placeholder="请输入学生姓名" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属班级" prop="belongId">
            <el-tree-select
                v-model="queryParams.belongId"
                :data="classOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择班级"
                check-strictly
                default-expand-all
            />
          </el-form-item>
          <el-form-item label="住宿类型" prop="accommodationType">
            <el-select v-model="queryParams.accommodationType" placeholder="请选择住宿类型" clearable>
              <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="学号" prop="studentNo">
            <el-input v-model="queryParams.studentNo" placeholder="请输入学号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="考勤分组" prop="attendanceGroupId">
            <el-tree-select
              v-model="queryParams.attendanceGroupId"
              :data="groupOptions"
              :props="{ value: 'id', label: 'label', children: 'children' }"
              value-key="id"
              check-strictly
              clearable
            />
          </el-form-item>
          <el-form-item label="打卡时间" style="width: 308px;">
            <el-date-picker
              v-model="dateRange"
              value-format="YYYY-MM-DD"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['attendance:studentAttendanceDetail:add']">新增</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['attendance:studentAttendanceDetail:edit']">修改</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['attendance:studentAttendanceDetail:remove']">删除</el-button>-->
          <!--          </el-col>-->
          <!--          <el-col :span="1.5">-->
          <!--            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['attendance:studentAttendanceDetail:export']">导出</el-button>-->
          <!--          </el-col>-->
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table height="calc(100vh - 420px)" v-loading="loading" :data="studentAttendanceDetailList"
                :cell-style="{ 'word-break': 'break-all' }"
                border @selection-change="handleSelectionChange" style="width: 100%">
        <el-table-column label="姓名" align="center" prop="studentName" />
        <el-table-column label="住宿类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="考勤组名称" align="center" prop="attendanceGroupName" width="120"/>
        <el-table-column label="所属班级" align="center" prop="className" width="120"/>
        <el-table-column label="学号" align="center" prop="studentNo" />
        <el-table-column label="人员状态" align="center" prop="studentStatus">
          <template #default="scope">
            <dict-tag :options="student_school_status" :value="scope.row.studentStatus" />
          </template>
        </el-table-column>
        <el-table-column label="打卡日期" align="center" prop="punchDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.punchDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="考勤班次" align="center" prop="shiftSegments" min-width="220" />
        <template v-for="(segment, idx) of shiftSegments">
          <el-table-column :label="segment.startLabel" align="center">
            <el-table-column label="打卡时间" min-width="160">
              <template #default="scope">
                <template v-if="scope.row.results[idx]">
                  <span>{{ scope.row.results[idx].startPunchTime }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="打卡结果" align="center">
              <template #default="scope">
                <template v-if="scope.row.results[idx]">
                  <dict-tag :options="attendance_result" :value="scope.row.results[idx].startPunchResult" />
                </template>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column :label="segment.endLabel" align="center">
            <el-table-column label="打卡时间" min-width="160">
              <template #default="scope">
                <template v-if="scope.row.results[idx]">
                  <span>{{ parseTime(scope.row.results[idx].endPunchTime) }}</span>
                </template>
              </template>
            </el-table-column>
            <el-table-column label="打卡结果" align="center">
              <template #default="scope">
                <template v-if="scope.row.results[idx]">
                  <dict-tag :options="attendance_result" :value="scope.row.results[idx].endPunchResult" />
                </template>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
        <el-table-column label="关联的审批请假单" align="left" width="600">
          <template #default="scope">
            <template v-for="item in scope.row.leaves">
              <el-button text type="primary" @click="handleViewLeave(item.id)" style="margin-left: 0;">
                <span>{{ '请假时间:' + item.startTime + '-' + item.endTime + ',' + '请假类型:' + leave_type.find(e => e.value === item.leaveType)?.label  + ',' + '请假事由:' + item.leaveReason }}</span>
              </el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <!-- 添加或修改学生考勤明细，一天一条对话框 -->
    <el-dialog :title="dialog.title" v-model="dialog.visible" width="500px" append-to-body>
      <el-form ref="studentAttendanceDetailFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="学生id" prop="studentId">
          <el-input v-model="form.studentId" placeholder="请输入学生id" />
        </el-form-item>
        <el-form-item label="学生姓名" prop="studentName">
          <el-input v-model="form.studentName" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-input v-model="form.gender" placeholder="请输入性别" />
        </el-form-item>
        <el-form-item label="班级id" prop="classId">
          <el-input v-model="form.classId" placeholder="请输入班级id" />
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="form.className" placeholder="请输入班级名称" />
        </el-form-item>
        <el-form-item label="学号" prop="studentNo">
          <el-input v-model="form.studentNo" placeholder="请输入学号" />
        </el-form-item>
        <el-form-item label="打卡日期" prop="punchDate">
          <el-date-picker clearable v-model="form.punchDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择打卡日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考勤班次，以json数组存储" prop="attendanceShift">
          <el-input v-model="form.attendanceShift" placeholder="请输入考勤班次，以json数组存储" />
        </el-form-item>
        <el-form-item label="迟到次数" prop="lateTimes">
          <el-input v-model="form.lateTimes" placeholder="请输入迟到次数" />
        </el-form-item>
        <el-form-item label="迟到时长，单位：分钟" prop="lateDuration">
          <el-input v-model="form.lateDuration" placeholder="请输入迟到时长，单位：分钟" />
        </el-form-item>
        <el-form-item label="上学打卡次数" prop="attendPunchNum">
          <el-input v-model="form.attendPunchNum" placeholder="请输入上学打卡次数" />
        </el-form-item>
        <el-form-item label="放学打卡次数" prop="afterPunchNum">
          <el-input v-model="form.afterPunchNum" placeholder="请输入放学打卡次数" />
        </el-form-item>
        <el-form-item label="上学缺卡次数" prop="attendAbsenceNum">
          <el-input v-model="form.attendAbsenceNum" placeholder="请输入上学缺卡次数" />
        </el-form-item>
        <el-form-item label="放学缺卡次数" prop="afterAbsenceNum">
          <el-input v-model="form.afterAbsenceNum" placeholder="请输入放学缺卡次数" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <StudentLeaveDetailDialog ref="studentLeaveDetailDialogRef" />
  </div>
</template>

<script setup name="StudentAttendanceDetail" lang="ts">
import {
  listStudentAttendanceDetail,
  getStudentAttendanceDetail,
  delStudentAttendanceDetail,
  addStudentAttendanceDetail,
  updateStudentAttendanceDetail
} from '@/api/attendance/student/detail';
import { StudentAttendanceDetailVO, StudentAttendanceDetailQuery, StudentAttendanceDetailForm } from '@/api/attendance/student/detail/types';
import { classTree, listClassInfo } from '@/api/office/class';
import { groupTreeSelect } from '@/api/attendance/setting/group';
import StudentLeaveDetailDialog from "../../leave/student/modules/StudentLeaveDetailDialog.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const {
  student_accommodation_type,
  student_sex,
  student_subscribe_status,
  student_school_status,
  faculty_type,
  face_pic_status,
  student_guardian_relation,
  device_type,
  sg_punch_type,
  attendance_result,
  leave_type
} = toRefs<any>(
  proxy?.useDict(
    'student_accommodation_type',
    'student_sex',
    'student_subscribe_status',
    'student_school_status',
    'faculty_type',
    'face_pic_status',
    'student_guardian_relation',
    'device_type',
    'sg_punch_type',
    'attendance_result',
    'leave_type'
  )
);
const studentAttendanceDetailList = ref<StudentAttendanceDetailVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const dateRange = ref<[DateModelType, DateModelType]>(['', '']);
const queryFormRef = ref<ElFormInstance>();
const studentAttendanceDetailFormRef = ref<ElFormInstance>();
const groupOptions = ref<any[]>([]);
const classOptions = ref<any[]>([]);
const studentLeaveDetailDialogRef = ref();
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});
const shiftSegments = ref([
  {
    startLabel: '上学1',
    endLabel: '放学1'
  },
  {
    startLabel: '上学2',
    endLabel: '放学2'
  },
  {
    startLabel: '上学3',
    endLabel: '放学3'
  }
]);
const initFormData: StudentAttendanceDetailForm = {
  id: undefined,
  studentId: undefined,
  studentName: undefined,
  gender: undefined,
  classId: undefined,
  className: undefined,
  studentNo: undefined,
  studentStatus: undefined,
  accommodationType: undefined,
  punchDate: undefined,
  attendanceShift: undefined,
  attendanceStatus: undefined,
  lateTimes: undefined,
  lateDuration: undefined,
  attendPunchNum: undefined,
  afterPunchNum: undefined,
  attendAbsenceNum: undefined,
  afterAbsenceNum: undefined
};
const data = reactive<PageData<StudentAttendanceDetailForm, StudentAttendanceDetailQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    studentId: undefined,
    studentName: undefined,
    gender: undefined,
    classId: undefined,
    className: undefined,
    studentNo: undefined,
    studentStatus: undefined,
    accommodationType: undefined,
    punchDate: undefined,
    attendanceShift: undefined,
    attendanceStatus: undefined,
    lateTimes: undefined,
    lateDuration: undefined,
    attendPunchNum: undefined,
    afterPunchNum: undefined,
    attendAbsenceNum: undefined,
    afterAbsenceNum: undefined,
    params: {}
  },
  rules: {
    id: [{ required: true, message: '不能为空', trigger: 'blur' }],
    studentId: [{ required: true, message: '学生id不能为空', trigger: 'blur' }],
    studentName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'blur' }],
    classId: [{ required: true, message: '班级id不能为空', trigger: 'blur' }],
    className: [{ required: true, message: '班级名称不能为空', trigger: 'blur' }],
    studentNo: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    studentStatus: [{ required: true, message: '学生状态不能为空', trigger: 'change' }],
    accommodationType: [{ required: true, message: '住宿类型不能为空', trigger: 'change' }],
    punchDate: [{ required: true, message: '打卡日期不能为空', trigger: 'blur' }],
    attendanceShift: [{ required: true, message: '考勤班次，以json数组存储不能为空', trigger: 'blur' }],
    attendanceStatus: [{ required: true, message: '考勤状态，1、出勤；2、缺勤；3、请假不能为空', trigger: 'change' }],
    lateTimes: [{ required: true, message: '迟到次数不能为空', trigger: 'blur' }],
    lateDuration: [{ required: true, message: '迟到时长，单位：分钟不能为空', trigger: 'blur' }],
    attendPunchNum: [{ required: true, message: '上学打卡次数不能为空', trigger: 'blur' }],
    afterPunchNum: [{ required: true, message: '放学打卡次数不能为空', trigger: 'blur' }],
    attendAbsenceNum: [{ required: true, message: '上学缺卡次数不能为空', trigger: 'blur' }],
    afterAbsenceNum: [{ required: true, message: '放学缺卡次数不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询部门下拉树结构 */
const getGroupTree = async () => {
  const res = await groupTreeSelect({ groupType: '1' });
  groupOptions.value = res.data;
};

const searchClassInfo = (queryString, cb) => {
  listClassInfo({ className: queryString }).then((response) => {
    cb(response.rows);
  });
};

const getClassTree = async () => {
  const res = await classTree();
  classOptions.value = res.data;
};

/** 查询学生考勤明细，一天一条列表 */
const getList = async () => {
  loading.value = true;
  proxy?.addDateRange(queryParams.value, dateRange.value, 'PunchDate');
  const res = await listStudentAttendanceDetail(queryParams.value);
  studentAttendanceDetailList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  studentAttendanceDetailFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = ['', ''];
  queryParams.value.classId = undefined;
  queryParams.value.className = undefined;
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: StudentAttendanceDetailVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加学生考勤明细，一天一条';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentAttendanceDetailVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStudentAttendanceDetail(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改学生考勤明细，一天一条';
};

const handleViewLeave = async (id) => {
  studentLeaveDetailDialogRef.value.handleUpdate(id);
};

/** 提交按钮 */
const submitForm = () => {
  studentAttendanceDetailFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStudentAttendanceDetail(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addStudentAttendanceDetail(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('修改成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentAttendanceDetailVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除学生考勤明细，一天一条编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delStudentAttendanceDetail(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'attendance/studentAttendanceDetail/export',
    {
      ...queryParams.value
    },
    `studentAttendanceDetail_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getGroupTree();
  getClassTree();
  getList();
});
</script>

